<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>轻量级区块链配置溯源</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
  <style>
    .result-item {
      margin: 10px 0;
      padding: 10px;
      border: 1px solid #eee;
      border-radius: 5px;
      background: #f8f9fa;
    }
    .added-line {
      color: #d9534f;
      font-family: monospace;
      font-size: 0.9em;
    }
    .chart-container {
      margin: 30px 0;
      text-align: center;
    }
    .chart-container img {
      max-width: 100%;
      border: 1px solid #ddd;
      border-radius: 8px;
    }
  </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">🚀 网络设备配置版本溯源系统</a>
  </div>
</nav>

<div class="container mt-4">
  <!-- 卡片 1：获取令牌 -->
  <div class="card mb-3">
    <div class="card-header">1. 获取访问令牌</div>
    <div class="card-body">
      <button id="getTokenBtn" class="btn btn-primary">获取 JWT</button>
      <div id="tokenArea" class="mt-2"></div>
    </div>
  </div>

  <!-- 卡片 2：上传配置（用于上链） -->
  <div class="card mb-3">
    <div class="card-header">2. 上传配置到区块链</div>
    <div class="card-body">
      <form id="uploadForm">
        <div class="row">
          <div class="col-md-4">
            <label class="form-label">设备 ID</label>
            <input name="device_id" class="form-control" value="Router1" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">操作员</label>
            <input name="operator" class="form-control" value="admin" required>
          </div>
          <div class="col-md-4">
            <label class="form-label">配置内容</label>
            <textarea name="config" class="form-control" rows="4" required></textarea>
          </div>
        </div>
        <button type="submit" class="btn btn-success mt-2">上传并上链</button>
      </form>
      <div id="uploadResult" class="mt-2"></div>
    </div>
  </div>

  <!-- 卡片 3：交互式存储对比演示 -->
  <div class="card mb-3">
    <div class="card-header">3. 交互式存储对比演示</div>
    <div class="card-body">
      <p>输入多个配置版本，系统将自动计算全量 vs 差异存储大小。</p>
      <textarea id="demoConfig" class="form-control" rows="4" placeholder="请输入设备配置..."></textarea>
      <div class="mt-2">
        <button id="addDemoConfig" class="btn btn-info">添加版本</button>
        <button id="generateChart" class="btn btn-primary">生成对比图表</button>
      </div>
      <div id="demoResults" class="mt-3"></div>
      <div class="chart-container" id="chartContainer"></div>
    </div>
  </div>

  <!-- 卡片 4：区块链 -->
  <div class="card mb-3">
    <div class="card-header">
      4. 区块链列表
      <div class="float-end">
        <input id="deviceFilter" class="form-control-sm" placeholder="设备过滤">
        <button id="loadChainBtn" class="btn btn-sm btn-outline-primary ms-1">加载</button>
      </div>
    </div>
    <div class="card-body">
      <div id="chainArea" class="chain-container"></div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // ===== JWT 获取 =====
  document.getElementById("getTokenBtn").onclick = () => {
    fetch("/generate-token")
      .then(r => r.json())
      .then(data => {
        document.getElementById("tokenArea").innerHTML =
          `<div class="alert alert-success">Bearer ${data.token}</div>`;
        localStorage.setItem("authToken", data.token);
      });
  };

  // ===== 上传配置 =====
  document.getElementById("uploadForm").onsubmit = (e) => {
    e.preventDefault();
    const form = e.target;
    const data = Object.fromEntries(new FormData(form));
    const token = localStorage.getItem("authToken");

    fetch("/upload-config", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify(data)
    })
    .then(r => r.json())
    .then(res => {
      document.getElementById("uploadResult").innerHTML =
        `<div class="alert alert-success">上链成功！Block Hash: ${res.block.hash.slice(0,12)}...</div>`;
    })
    .catch(err => {
      document.getElementById("uploadResult").innerHTML =
        `<div class="alert alert-danger">错误: ${err.message}</div>`;
    });
  };

  // ===== 交互式对比演示 =====
  const demoResults = [];

  document.getElementById("addDemoConfig").onclick = () => {
    const config = document.getElementById("demoConfig").value;
    const device_id = "Router1";
    const operator = "admin";

    if (!config) return alert("请输入配置");

    fetch("/api/add-config", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ config, device_id, operator })
    })
    .then(r => r.json())
    .then(data => {
      if (data.error) return alert(data.error);
      demoResults.push(data);
      updateDemoResults();
      document.getElementById("demoConfig").value = "";
    });
  };

  function updateDemoResults() {
    const div = document.getElementById("demoResults");
    div.innerHTML = demoResults.map(r => `
      <div class="result-item">
        <strong>V${r.index}</strong> 全量: ${r.full} B | 差异: ${r.diff} B
        <div>新增配置: 
          ${r.added_lines.map(l => `<span class="added-line">+ ${l}</span>`).join("<br>")}
        </div>
      </div>
    `).join("");
  }

  document.getElementById("generateChart").onclick = () => {
    if (demoResults.length === 0) return alert("请先添加至少一个配置版本！");
    fetch("/api/generate-chart", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ results: demoResults })
    })
    .then(r => r.json())
    .then(data => {
      document.getElementById("chartContainer").innerHTML = `
        <h5>📊 存储对比图表</h5>
        <img src="${data.png_url}?t=${Date.now()}" />
        <p>
          <a href="${data.csv_url}" class="btn btn-sm btn-outline-secondary" download>📥 下载 CSV</a>
          <a href="${data.png_url}" class="btn btn-sm btn-outline-secondary" download>📥 下载 PNG</a>
        </p>
      `;
    });
  };

  // ===== 加载区块链 =====
  document.getElementById("loadChainBtn").onclick = () => {
    const device = document.getElementById("deviceFilter").value;
    const url = device ? `/chain_latest?device=${device}` : "/chain_latest";
    const token = localStorage.getItem("authToken");

    fetch(url, {
      headers: { "Authorization": `Bearer ${token}` }
    })
    .then(r => r.json())
    .then(chain => {
      document.getElementById("chainArea").innerHTML = chain.map(block => `
        <div class="p-2 border-bottom">
          <strong>Block #${block.index}</strong> 
          ${block.hash.slice(0,12)}... | 
          ${new Date(block.timestamp * 1000).toLocaleString()} |
          ${block.data.device_id} | 
          <code>${block.data.diff.substring(0, 50)}...</code>
        </div>
      `).join("");
    });
  };
</script>
</body>
</html>